<?php

class BootstrapApi extends Zend_Application_Bootstrap_Bootstrap
{
    public static function _initQuery()
    {
        $url = parse_url($_SERVER['REQUEST_URI']);
        preg_match('#/(\d)/([^/]*)[/]?(.*$)#iu',$url['path'], $matches); //  /version/module
//        var_dump($url, $_SERVER['REQUEST_URI']);
        if (count($matches)) {
            define('API_VERSION', $matches[1]);
            $_SERVER['REQUEST_URI'] = '/'.$matches[2].'/rest'. (!empty($matches[3]) ? '/'.$matches[3] : '');
            if (!empty($url['query'])) {
                $_SERVER['REQUEST_URI'] .= '?'.$url['query'];
            }
        }
//        var_dump($matches,$_SERVER['REQUEST_URI']);exit;
        return $_SERVER['REQUEST_URI'];
    }

    public function _initLoader()
    {
        new Zend_Application_Module_Autoloader(array(
                    'namespace' => '',
                    'basePath' => APPLICATION_PATH,
                    'resourceTypes' => array(
                        'model' => array(
                            'path'      => 'models',
                            'namespace' => 'Model',
                            ),
                        )
                    ));


        $autoloader = Zend_Loader_Autoloader::getInstance();
        $autoloader->registerNamespace('Ac_');
        $autoloader->registerNamespace('Shanty_');
        $autoloader->registerNamespace('Apache_');
        $autoloader->registerNamespace('Stunti_');
        Zend_Session::start();
    }


    protected function _initRoutes()
    {

        $this->bootstrap('frontController');
        $frontController = Zend_Controller_Front::getInstance();
        //$restRoute = new Zend_Rest_Route($frontController);
        //$frontController->getRouter()->addRoute('default', $restRoute);        
                
                  $routeConfig = new Zend_Config_Ini(APPLICATION_PATH . '/configs/route_api.ini', 'production');
                  $router = new Zend_Controller_Router_Rewrite();
                  $router->addConfig($routeConfig, 'routes');
                  $frontController->setRouter($router);
               
        /*
        // get your controller
        $ctrl = Zend_Controller_Front::getInstance();

        $router = $ctrl->getRouter();
        // initialise a new zend config object
        $routeConfig = new Zend_Config_Ini(APPLICATION_PATH . '/configs/route.ini', 'production');
        // via the add config method your routes are added automagically
        $router->addConfig($routeConfig, 'routes');
         *
         */
        return $frontController->getRouter();
    }

   public function _initCustomRequest()
    {

        $matches = array();
        $this->bootstrap('FrontController');
        $front = $this->getResource('FrontController');


        preg_match('/\.json|\.xml|\.html|\.rss/', $_SERVER['REQUEST_URI'], $matches);

        if (count($matches)) {
            // Change request uri
            $_SERVER['REQUEST_URI'] = str_replace($matches[0], '', $_SERVER['REQUEST_URI']);

            // Set default request
            $request = $front->getRequest();
            if (null === $front->getRequest()) {
                $request = new Zend_Controller_Request_Http();
                $front->setRequest($request);
            }


            //$front = Zend_Controller_Front::getInstance();
            $front->getRequest()->setParam('format',
                    strtolower(trim($matches[0], '.')));
        }

//        var_dump($_SERVER['REQUEST_URI']);exit;
    }


    /**
     * Initialise the database
     */
    public function _initMongo()
    {
        $connection = new Shanty_Mongo_Connection('mongodb://'.MONGO_HOST.':'.MONGO_PORT);
        //$connection = new Shanty_Mongo_Connection('mongodb:///tmp/mongodb-'.MONGO_PORT.'.sock', array('persist'=>'per'));
        //$connection->connect();
        //Shanty_Mongo::addMaster($connection);
        //Shanty_Mongo::addMaster($connection);
        Shanty_Mongo::addMaster($connection, 1, 'accounts');        
        Shanty_Mongo::addMaster($connection, 1, 'default');        
    }

    public function _initCache()
    {
        /*
        $backendOptions = array(
            'host' => MONGO_HOST,'port' => MONGO_PORT, 'persistent' => true
        );
        */
        $backendOptions = array(
            'persistent' => true,
            'lifetime' => 300,
        );

        $frontendOptions = array(

            'automatic_serialization' => true,
            'automatic_cleaning'      => 1,
            'caching'                 => (defined('CACHING_ENABLED') ? CACHING_ENABLED : false)
        );

        $redis = new Redis();
        $connection = $redis->connect('localhost', 6379);
        Zend_Registry::set('redis', $redis);

        //$cache = Zend_Cache::factory('Output', 'Stunti_Cache_Backend_Mongo', $frontendOptions, $backendOptions, false, true, true);
        $cache = Zend_Cache::factory('Core', 'Stunti_Cache_Backend_Redis', $frontendOptions, $backendOptions, false, true, true);

        Zend_Registry::set('Zend_Cache', $cache);
        Zend_Paginator::setCache($cache);
        Zend_Registry::set('cache', $cache);
        //Engine_Mongo::setCache($cache);
    }


    /**
     *
     * @param void $_cache Initialize the translation engine
     */
    function _initTranslation()
    {
        try {
            $translate = new Zend_Translate('Ac_Translate_Adapter_Mongo', '');

            //$translate->getAdapter()->setCache($_cache);
            Zend_Registry::set('translate', $translate);
            //Zend_Registry::set('Zend_Translate', $translate);
            //Zend_Validate_Abstract::setDefaultTranslator($translate);
        } catch (Exception $e) {
            var_dump($e);
            exit;
        }
    }

}

